package org.apache.ocean.solr.util;

import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongListIterator;

import java.util.Arrays;

/**
 * Uses binarysearch to keep int list sorted on add and remove
 * 
 */
public class SortedLongList {
	private LongArrayList list;
  
	public SortedLongList(LongArrayList list) {
    this.list = list;
  }
	
	public SortedLongList() {
		this.list = new LongArrayList();
	}

	public SortedLongList(long[] array) {
		this.list = new LongArrayList(array);
	}
  
	public long[] toLongArray() {
		return list.toLongArray();
	}
	
	public LongListIterator tailIterator(int i) {
		int index = Arrays.binarySearch(list.elements(), i);
		if (index < 0) {
			index = -index - 1;
		}
	  return list.listIterator(index);
	}

	public int size() {
		return list.size();
	}

	public LongIterator iterator() {
		return list.iterator();
	}

	public boolean contains(long i) {
		int index = Arrays.binarySearch(list.elements(), i);
		return index >= 0;
	}

	public long remove(long i) {
		int index = Arrays.binarySearch(list.elements(), i);
		return list.removeLong(index);
	}
  
	public long get(int index) {
	  return list.getLong(index);
	}
	
	// TODO: needs to return where added
	public int add(long i) {
		int index = Arrays.binarySearch(list.elements(), i);
		if (index < 0) {
			int insertIndex = -index - 1;
			list.add(insertIndex, i);
			return insertIndex;
		} else {
			return index;
		}
	}
}
